<!-- 日志模块 -->
<script>
import axios from 'axios';
import { getData, postData } from '@/service/getData';
import ExcelJS from 'exceljs';
export default {
  data() {
    return {
      activeName: 'first',
      role: 'admin',
      dialogVisible: false,
      dialogVisible2: false,
      dialogVisible3: false,
      checkForm: {
        review_id: '',
        action: '通过',
        question_modified: '',
        answer_modified: '',
        rejection_reason: '',
      },
      form: {
        question: '',
        answer: '',
        reviewer_name: '管理员1',
      },
      form2: {
        review_id: '',
        question_modified: '',
        answer_modified: '',
      },
      //  全部列表
      allPairsList: [],
      //  待审核列表
      waitPairsList: [],
      // 审核未通过
      failPairsList: [],
      historyList: [],
      all_reviews: [],
      feedbackList: [],
      uploadParams: {
        uploadUrl: '/agent/corrector/upload_original_file',
        data: {},
        headers: {
          Authorization: '',
        },
        name: 'file',
        fileLists: [],
      },
      qapairOption: {
        page: 1,
        total: 0,
      },
      logOption: {
        page: 1,
        total: 0,
      },
    };
  },

  mounted() {
    //  初始化
    let token = localStorage.getItem('token');
    this.uploadParams.headers['Authorization'] = 'Token ' + token;
    if (this.$store.state.user.groups[0]) {
      switch (this.$store.state.user.groups[0].name) {
        case '超级管理员':
          this.role = 'super';
          break;
        case '管理员':
          this.role = 'admin';
          break;
        default:
          this.role = 'user';
          break;
      }
    }
    this.getAllPairsList();
    this.getFeedbackList();
    this.getHistotyList();
  },
  methods: {
    handleCurrentChange(val) {
      this.qapairOption.page = val;
      this.getAllPairsList();
      console.log(`当前页: ${val}`);
    },
    handleCurrentChange2(val) {
      this.logOption.page = val;
      this.getHistotyList();
      console.log(`当前页: ${val}`);
    },
    getHistotyList() {
      getData(
        'api/sysmanage/operationlog/',
        {
          page: this.logOption.page,
          page_size: 10,
        },
        'get',
      )
        .then((res) => {
          this.logOption.total = res.data.pagination.total;
          this.historyList = res.data.results;
        })
        .catch((e) => {})
        .finally((v) => {});
    },
    downLoadFile() {
      // 处理数据
      // 示例数据
      let data = [['提问人', '问题', '内容', '时间']];

      console.log(data, 'data');
      // 创建工作簿
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('Sheet1');

      // 添加数据
      worksheet.columns = [
        { header: '提问人', key: 'user' },
        { header: '问题', key: 'title' },
        { header: '内容', key: 'content' },
        { header: '时间', key: 'created_time' },
      ];
      this.feedbackList.forEach((item) => {
        worksheet.addRow({
          user: item.user,
          title: item.title,
          content: item.content,
          created_time: item.created_time,
        });
      });

      // 导出文件
      workbook.xlsx.writeBuffer().then((buffer) => {
        const blob = new Blob([buffer], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = '导出数据.xlsx';
        link.click();
      });
    },
    downLoadFile2() {
      // 处理数据
      // 示例数据
      let data = [['角色', '行为', '描述', '时间']];

      console.log(data, 'data');
      // 创建工作簿
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('Sheet1');

      // 添加数据
      worksheet.columns = [
        { header: '角色', key: 'user' },
        { header: '行为', key: 'action' },
        { header: '描述', key: 'description' },
        { header: '时间', key: 'timestamp' },
      ];
      console.log('历史记录', this.historyList);
      this.historyList.forEach((item) => {
        worksheet.addRow({
          user: item.user,
          action: item.action,
          description: item.description,
          timestamp: item.timestamp,
        });
      });

      // 导出文件
      workbook.xlsx.writeBuffer().then((buffer) => {
        const blob = new Blob([buffer], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = '操作记录.xlsx';
        link.click();
      });
    },
    deleteItem(id) {
      axios
        .post(
          '/api/qa/drop_qapair/',
          {
            id: id,
          },
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          this.$message({
            message: '删除成功',
            type: 'success',
          });
          this.getAllPairsList();
        })
        .catch((e) => {})
        .finally((v) => {});
    },
    getFeedbackList() {
      getData('/api/sysmanage/feedback/list_feedback', {}, 'get')
        .then((res) => {
          // 将数组反转
          this.feedbackList = res;
        })
        .catch((e) => {})
        .finally((v) => {});
    },
    getAllPairsList() {
      getData(
        '/api/qa/get_qapair_list/',
        {
          page: this.qapairOption.page,
          page_size: 10,
        },
        'get',
      )
        .then((res) => {
          // 将数组反转
          this.qapairOption.total = res.data.pagination.total;
          this.all_reviews = res.data.results;
        })
        .catch((e) => {})
        .finally((v) => {});
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    someMethod() {
      const obj = this.someObject; // 假设 someObject 是可能未定义的对象
      if (obj && obj.utils) {
        const result = obj.utils.someFunction();
        // 处理结果
      } else {
        // 处理对象或 utils 未定义的情况
        console.warn('对象或 utils 属性未定义');
      }
    },
  },
};
</script>

<template>
  <div class="mainStyle">
    <div class="contentRight columnFlex">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="问答记录" name="first">
          <el-table
            :data="all_reviews"
            class="table-container table-item"
            style="margin-top: 10px; margin-bottom: 10px"
            size="small"
            border
          >
            <el-table-column prop="id" label="ID" width="80"> </el-table-column>
            <el-table-column prop="user" label="角色"> </el-table-column>
            <el-table-column prop="question" label="问题" width="280">
              <template slot-scope="scope">
                <span class="over-text" :title="scope.row.question">{{ scope.row.question }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="answer" label="答案" width="280">
              <template slot-scope="scope">
                <span class="over-text" :title="scope.row.answer">{{ scope.row.answer }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="comment" label="反馈">
              <template slot-scope="scope">
                <span class="over-text" :title="scope.row.comment">{{ scope.row.comment }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="topk_references" label="相关文档">
              <template slot-scope="scope">
                <el-tag
                  style="margin-right: 10px; margin-bottom: 10px"
                  size="small"
                  v-for="item in scope.row.topk_references"
                  :key="item.id"
                  >{{ item.file_name }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间"> </el-table-column>

            <el-table-column prop="updated_at" label="反馈时间"> </el-table-column>
            <el-table-column prop="updated_at" label="操作">
              <template slot-scope="scope">
                <el-button type="danger" size="small" @click="deleteItem(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="qapairOption.total"
            :current-page.sync="qapairOption.page"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="系统反馈" name="second">
          <div class="fl-line">
            <el-button size="small" @click="downLoadFile">导出Excel</el-button>
          </div>

          <el-table
            :data="feedbackList"
            class="table-container table-item"
            size="small"
            border
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID" width="80"> </el-table-column>
            <el-table-column prop="user" label="提问人"> </el-table-column>
            <el-table-column prop="title" label="问题"> </el-table-column>
            <el-table-column prop="content" label="内容"> </el-table-column>
            <el-table-column prop="created_time" label="时间"> </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="操作记录" name="操作记录">
          <div class="fl-line">
            <el-button size="small" @click="downLoadFile2">导出Excel</el-button>
          </div>
          <!-- div -->
          <el-table
            :data="historyList"
            class="table-container table-item"
            style="margin-top: 10px; margin-bottom: 10px"
            size="small"
            border
          >
            <el-table-column prop="user" label="角色"> </el-table-column>
            <el-table-column prop="action" label="行为"> </el-table-column>
            <el-table-column prop="description" label="描述"> </el-table-column>
            <el-table-column prop="timestamp" label="时间"> </el-table-column>
          </el-table>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="logOption.total"
            :current-page.sync="logOption.page"
            @current-change="handleCurrentChange2"
          >
          </el-pagination>
        </el-tab-pane>
      </el-tabs>

      <!-- 创建问题 -->

      <!-- 全部列表 -->
      <!-- 待审核列表 -->
    </div>
  </div>
</template>

<style lang="scss" scoped>
.mainStyle {
  color: #666;
  background-color: #fff;
  width: calc(100% - 20px);
  margin: 10px;
  height: calc(100% - 20px);
}
.table-container {
  margin-top: 10px;
  height: 500px;
}
//  样式穿透
.btn-line {
  padding: 20px 0;
  .submit-btn {
    width: 200px;
    float: right;
  }
}
.over-text {
  display: inline-block;
  width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 20px;
}
.table-item {
  height: calc(100vh - 240px);
  overflow: auto;
}
.fl-line {
  padding-top: 10px;
  text-align: right;
}
</style>
